// FixFlex.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

wstring GetOutputFileName(const wstring& input_filename)
{
    size_t index = input_filename.find_last_of(L".");
    wstring input_ext = input_filename.substr(index, input_filename.length()-index);

    if (input_ext==L".out") {
        wstring output_filename(input_filename.substr(0, index));

        return output_filename.append(L".cpp");
    } else {
        return L"";
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    if (argc == 2) {
        wstring input_filename(argv[1]);
        wstring output_filename = GetOutputFileName(input_filename);

        if (output_filename.size() > 0) {
            wifstream input_file_stream(input_filename);
            wofstream output_file_stream(output_filename, ios::trunc);

            wchar_t buffer[1024] = {0};
            bool found = false;

            while (input_file_stream.getline(buffer, 1024)) {
                if (wstring(buffer) == L"class istream;" && found == false) {
                    wstring cstring = L"#include <iostream>\n";

                    cstring.append(L"using namespace std;\n");

                    output_file_stream.write(cstring.c_str(), cstring.length());

                    found = true;
                } else {
                    output_file_stream.write(buffer, wstring(buffer).length());
                    output_file_stream.write(L"\n", wstring(L"\n").length());
                }
            }

            input_file_stream.close();
            output_file_stream.close();

            wcout<<L"<FIXED FILE SUCCESSFULLY>: "<<output_filename.c_str()<<L" :-)"<<endl;
        } else {
            wcerr<<L"[INVALID INPUT FILE NAME]:"<<input_filename.c_str()<<L" :-("<<endl;
        }
    } else {
        wcerr<<L"[INVALID INPUT ARGUMENTS]"<<L" :-("<<endl;
    }

    return 0;
}

